/****************************************************
	文件：SchemeMgr.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/10/11 17:18:36
	功能：配置表 管理器
*****************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using HTUtility;
using HTFramework.ResKit;

namespace HTFramework
{
    public class SchemeMgr : Singleton<SchemeMgr>
    {
        private Dictionary<E_Scheme, object> mSchemeDataDict;

        public void Init()
        {
            mSchemeDataDict = new Dictionary<E_Scheme, object>();
            HTLogger.Info("SchemeMgr init done.");
        }

        /// <summary>
        /// 加载指定 Scheme 数据
        /// </summary>
        /// <param name="scheme">配置表</param>
        /// <returns></returns>
        public T Load<T>(E_Scheme scheme) where T : class, new()
        {
            object data = null;
            if (mSchemeDataDict.TryGetValue(scheme, out data))
            {
                HTLogger.Debug("配置表 {0} 已加载过，直接从缓存中获取配置表数据", Enum.GetName(typeof(E_Scheme), scheme));
                return (T)data;
            }
            else
            {
                string schemeName = Enum.GetName(typeof(E_Scheme), scheme); //枚举名和配置表文件名一致
                string path = string.Format("{0}{1}.bytes", FConsts.PATH_SCHEMES_BINARY_FOLDER, schemeName);
                HTLogger.Debug("加载配置表：{0}\nPath：{1}", schemeName, path);
                TextAsset textAsset = ResLoader.Instance.LoadSync<TextAsset>(path);
                if (textAsset == null)
                {
                    HTLogger.Error("加载配置表出错！配置表（{0}）不存在，\n路径：{1}", schemeName, path);
                    return null;
                }
                try
                {
                    using (MemoryStream ms = new MemoryStream(textAsset.bytes))
                    {
                        BinaryFormatter bf = new BinaryFormatter();
                        data = bf.Deserialize(ms);
                    }
                }
                catch (Exception e)
                {
                    HTLogger.Error("加载配置表 {0} 出错；\nError：{1}", schemeName, e.ToString());
                }
                mSchemeDataDict.Add(scheme, data);
                return (T)data;
            }
        }

        /// <summary>
        /// 获取配置表数据
        /// </summary>
        /// <param name="scheme">配置表</param>
        /// <returns></returns>
        public T Get<T>(E_Scheme scheme) where T : class, new()
        {
            object data = null;
            if (mSchemeDataDict.TryGetValue(scheme, out data) == false || data == null)
            {
                HTLogger.Error("尚未加载配置表：{0}", Enum.GetName(typeof(E_Scheme), scheme));
                return null;
            }
            return (T)data;
        }


    }
}
